package com.gl.glcourses.util;

import java.util.EnumSet;

import org.apache.commons.lang.StringUtils;

/**
 * Utility class for the enum and enumset types.
 */
public class EnumUtil {

	/**
	 * Obtain an element set from an array of strings.
	 * 
	 * @param strings
	 *            Array with the names of the elements.
	 * @return Set of elements.
	 */
	public static <E extends Enum<E>> EnumSet<E> fromStrings(Class<E> elementType, String strings[]) {
		EnumSet<E> ret = EnumSet.noneOf(elementType);
		if (strings != null) {
			for (String str : strings) {
				if (!StringUtils.isEmpty(str)) {
					ret.add(Enum.valueOf(elementType, str));
				}
			}
		}
		return ret;
	}

	/**
	 * Obtain an element from the name, ignoring the case.
	 * 
	 * @param string
	 *            Name of the element ignoring case.
	 * @return Element with the name ignoring the case.
	 */
	public static <E extends Enum<E>> E fromStringIgnoreCase(Class<E> elementType, String string) {
		E ret = null;
		for (E element : EnumSet.allOf(elementType)) {
			if (element.name().equalsIgnoreCase(string)) {
				ret = element;
				break;
			}
		}
		return ret;
	}

	/**
	 * Obtain a bit flag array of the elements set.
	 * 
	 * @param elements
	 *            Set with the elements.
	 * @return Bit flag array from the elements set.
	 */
	public static <E extends Enum<E>> Integer toInteger(EnumSet<E> elements) {
		Integer ret = 0;
		if (elements != null) {
			for (E element : elements) {
				ret += (int) Math.pow(2, element.ordinal());
			}
		}
		return ret;
	}

	/**
	 * Get a set of elements from a bit flag array.
	 * 
	 * @param intElements
	 *            Bit flag array.
	 * @return Set of elements.
	 */
	public static <E extends Enum<E>> EnumSet<E> fromInteger(Class<E> elementType, Integer intElements) {
		EnumSet<E> ret = EnumSet.noneOf(elementType);
		for (E element : EnumSet.allOf(elementType)) {
			if ((intElements & (int) Math.pow(2, element.ordinal())) > 0) {
				ret.add(element);
			}
		}
		return ret;
	}

	/**
	 * Get an element from the ordinal number.
	 * 
	 * @param i
	 *            Ordinal number.
	 * @return Corresponding element.
	 */
	public static <E extends Enum<E>> E fromInt(Class<E> elementType, int i) {
		E ret = null;
		for (E element : EnumSet.allOf(elementType)) {
			if (element.ordinal() == i) {
				ret = element;
				break;
			}
		}
		return ret;
	}

}
